package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    //请求地址定为常量
    public static final String wx_login= "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties properties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前用户的openId
        //使用HttpClientUtil的doGet方法来实现发送请求
        //封装发送的信息
        Map<String, String> map = new HashMap<>();
        map.put("appid",properties.getAppid());
        map.put("secret",properties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
//        log.info("map{}", JSONObject.toJSONString(map));
        //作为参数放到方法里面，并且获取json格式的openid数据
        String json = HttpClientUtil.doGet(wx_login,map);
//        log.info("json:{}",json);
        JSONObject jsonObject = JSONObject.parseObject(json);
//        log.info("jsonObject:{}",jsonObject);
        String openid = jsonObject.getString("openid");
        //判断openId是否为空，空：登陆失败，抛出异常
        if(openid==null){
            //登录异常的信息
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断是否为新用户：查数据库表
        User selectUser =userMapper.getUserById(openid);
        if(selectUser==null){
            User newUser = new User();
            newUser.setOpenid(openid);
            //新用户自动完成注册
            userMapper.insertUser(newUser);
            return newUser;
        }
        //返回用户对象
        return selectUser;
    }
}
